package com.csist.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.csist.pojo.po.basicInfoModule.EducationBackground;
import com.csist.service.po.basicInfoModule.EducationBackgroundService;
import com.csist.service.po.basicInfoModule.impl.EducationBackgroundServiceImpl;
import com.csist.util.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/educationBackground")
public class EducationBackgroundServlet extends HttpServlet {
    private JSONObject jsonObject;
    private EducationBackgroundService educationBackgroundService = new EducationBackgroundServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //        这里如果request没有json字符串，则jsonObject为null（获取不到）
        jsonObject = JSONUtil.getJSONObject(request);
        if (jsonObject == null) {
            err(request, response);
            return;
        }
        String type = jsonObject.getString("type");
        if (type != null) {
            switch (type) {
                case "add":
                    add(request, response);
                    break;
                case "query":
                    show(request, response);
                    break;
                case "edit":
                    edit(request, response);
                    break;
                case "editByState":
                    editByState(request, response);
                    break;
                case "conditionalShow":
                    conditionalShow(request, response);
                    break;
                default:
                    err(request, response);
            }
        } else {
            err(request, response);
        }


    }

    /**
     * 动态查询指定数据(这里只能用学历层次名称)
     *
     * @param request
     * @param response
     */
    private void conditionalShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        //        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;
        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");

        EducationBackground educationBackground = new EducationBackground();
        String ebName = group.getString("levelName");
//        Integer ebState = group.getInteger("ebState");
        educationBackground.setEbName(ebName);
//        educationBackground.setEbState(ebState == 1);
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<EducationBackground> list = educationBackgroundService.findEducationBackgroundFuzzy(educationBackground);
        if (list != null) {
            PageInfo<EducationBackground> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);

    }

    /**
     * 修改学历层次状态（逻辑删除）
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void editByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        int ebId = group.getInteger("ebId");
        int i = educationBackgroundService.updateEducationBackgroundByState(ebId);
        Boolean status;
        String msg;
        if (i > 0) {
            status = true;
            msg = "修改状态成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改状态失败...";
        statusMsg(request, response, status, msg);
    }

    /**
     * 修改学历层次信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        EducationBackground educationBackground = new EducationBackground();
//        从group中获取传输过来的学历层次名称
        String ebName = group.getString("ebName");
//        从group中获取传输过来的学历层次状态
        Integer ebState = group.getInteger("ebState");
        if (ebName == null || ebName.isEmpty() || ebState == null) {
            err(request, response);
            return;
        }
        educationBackground.setEbName(ebName);
//        为学历层次状态赋值
        educationBackground.setEbState(ebState == 1);
        List<EducationBackground> list = educationBackgroundService.findEducationBackground(educationBackground);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "查找出与修改数据有相符的，请修改成正确信息...";
            statusMsg(request, response, status, msg);
            return;
        }
        educationBackground.setEbId(group.getInteger("ebId"));
        int i = educationBackgroundService.updateEducationBackground(educationBackground);
        if (i > 0) {
            status = true;
            msg = "修改信息成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "修改信息失败...";
        statusMsg(request, response, status, msg);
    }

    /**
     * 添加学历层次数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        获取传输过来的JSON数据组
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        if (group == null) {
            err(request, response);
            return;
        }
        EducationBackground educationBackground = new EducationBackground();
//        从group中获取传输过来的学历层次名称
        String ebName = group.getString("ebName");
        if (ebName == null || ebName.isEmpty()) {
            err(request, response);
            return;
        }
        educationBackground.setEbName(ebName);
//        判断是否有重复的学历层次（根据学历层次名称），有就退出
        List<EducationBackground> list = educationBackgroundService.findEducationBackground(educationBackground);
        Boolean status;
        String msg;
        if (list != null) {
            status = false;
            msg = "添加数据已存在...";
            statusMsg(request, response, status, msg);
            return;
        }
        int i = educationBackgroundService.addEducationBackground(educationBackground);
        if (i > 0) {
            status = true;
            msg = "添加数据成功...";
            statusMsg(request, response, status, msg);
            return;
        }
        status = false;
        msg = "添加数据失败...";
        statusMsg(request, response, status, msg);

    }

    /**
     * 显示所有学历层次数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void show(HttpServletRequest request, HttpServletResponse response) throws IOException {

//        当jsonObject为空时
        if (jsonObject == null) {
            err(request, response);
            return;
        }
        //        存储数据、是否执行成功、判断结果
        HashMap<String, Object> map = new HashMap<>();

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;


        //        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");
        //开启分页，当前页码为num每页显示pageSize条数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<EducationBackground> list = educationBackgroundService.findAll();
        if (list != null) {
            PageInfo<EducationBackground> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);
    }

    private void err(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "传送了无效数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void findNoData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pagination", null);
        map.put("status", false);
        map.put("msg", "无匹配数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void statusMsg(HttpServletRequest request, HttpServletResponse response, Boolean status, String msg) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("msg", msg);
        response.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
